<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 12/8/18
 * Time: 5:24 PM
 */

require_once __DIR__.'/vendor/autoload.php';
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Worker;

$worker = new Worker();

$worker->onWorkerStart = function() {
    // 以websocket协议连接远程websocket服务器
    $con2 = new AsyncTcpConnection('ws://127.0.0.1:7777');
    $con = new AsyncTcpConnection("ws://ws.coincap.io:443/prices?assets=bitcoin,ethereum");
    $con->transport = 'ssl';
    // 注册连接上后的事件
    $con2->onConnect = function($con){
        echo "connected\n";
    };
    $con->onConnect = function($con){
        echo "connected\n";
    };
    // 远程websocket服务器发来消息时
    $con2->onMessage = function($con, $data){
        echo "recv: $data\n";
    };
    $con->onMessage = function($con, $data) use ($con2) {
        echo "recv: $data\n";
        $con2->send($data);
    };
    // 连接上发生错误时，一般是连接远程websocket服务器失败错误
    $con->onError = function($con, $code, $msg){
        echo "error: $msg\n";
    };
    // 当连接远程websocket服务器的连接断开时
    $con->onClose = function($con){
        echo "connection closed\n";
        $con->reconnect(1);
    };
    // 设置好以上各种回调后，执行连接操作
    $con2->connect();
    $con->connect();
};

Worker::runAll();